package com.h3c.nem.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.h3c.nem.client.DataCenterFeignClient;
import com.h3c.nem.entity.SdAllWorker;
import com.h3c.nem.mapper.SdAllWorkerMapper;
import com.h3c.nem.service.CommService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 查询合作员工是否离职
 */
@JobHandler(value="workerIsLeaveJob")
@Component
public class WorkerIsLeaveJob extends IJobHandler {

    @Autowired
    private SdAllWorkerMapper sdAllWorkerMapper;
    @Autowired
    private DataCenterFeignClient dataCenterFeignClient;
    @Autowired
    private CommService commService;

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        XxlJobLogger.log("workerIsLeaveJob开始执行");
        QueryWrapper<SdAllWorker> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SdAllWorker::getWorkerType, "2").ne(SdAllWorker::getWorkerId, "gw4144"); //合作员工
        List<SdAllWorker> workers = sdAllWorkerMapper.selectList(queryWrapper);
        XxlJobLogger.log("共有" + workers.size() + "名合作员工数据");
        List<SdAllWorker> allWorkerList = new ArrayList<>();
        List<String> workerIdList = new ArrayList<>();
        workers.forEach(worker -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("empCode", worker.getWorkerId());
            String result = dataCenterFeignClient.queryCooperativeWorker(jsonObject.toString(),
                    commService.getPerformanceToken());
            JSONObject basicInfoJson = JSONObject.parseObject(result);
            List<Map<String, String>> basicInfoList = (List<Map<String, String>>) basicInfoJson.get("data");
            if (CollectionUtils.isEmpty(basicInfoList)) {
                //查询不到就是离职员工
                workerIdList.add(worker.getWorkerId());
                allWorkerList.add(worker);
            }
        });
        //判断是否有离职员工在数据库中
        XxlJobLogger.log("共有" + workerIdList.size() + "名合作员工已经离职");
        if (!workerIdList.isEmpty()) {
            //删除数据
            QueryWrapper<SdAllWorker> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().in(SdAllWorker::getWorkerId, workerIdList);
            int delete = sdAllWorkerMapper.delete(queryWrapper1);
            XxlJobLogger.log("删除" + delete + "名合作员工");
            commService.deleteCacheMap(allWorkerList);
        }
        XxlJobLogger.log("workerIsLeaveJob执行结束");
        return ReturnT.SUCCESS;
    }
}
